<?php

namespace Regard\ProductsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Regard\ProductsBundle\Entity\Product;
use Regard\ProductsBundle\Entity\Brand;
use Regard\ProductsBundle\Form\ProductType;
use Regard\ProductsBundle\Form\BrandType;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ProductsController extends Controller
{
    public function listBrandAction()
    {
        $view = 'RegardProductsBundle:Products:listBrand.html.twig';
        
        $repoBrand = $this->getDoctrine()
                        ->getManager()
                        ->getRepository('RegardProductsBundle:Brand');
        
        // get the brand list to show
		if (true === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
			$brandList = $repoBrand->findBy(array(), array('name' => 'asc'));
		} else {
			$brandList = $repoBrand->findBy(array('toShow' => true), array('name' => 'asc'));
		}
        
        $parameters = array(
            'brandList' => $brandList
        );
        
        return $this->render($view, $parameters);
    }

    public function listProductsByBrandAction($brandId, $brandName)
    {
        $view = 'RegardProductsBundle:Products:listProductsByBrand.html.twig';
        
        $repoProducts = $this->getDoctrine()
                        ->getManager()
                        ->getRepository('RegardProductsBundle:Product');
        
        $products = $repoProducts->findBy(array('brandId' => $brandId), array('id' => 'desc'));
        
        // if no news has this id
        if($products === null)
        {
          throw $this->createNotFoundException('Brand[id='.$brandId.'] does not exist.');
        }
        
        $parameters = array(
            'productList' => $products,
			'brandId' => $brandId,
			'brandName' => $brandName
        );
        
        return $this->render($view, $parameters);
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
     * @return render view
     */
    public function addProductsAction($brandId) 
    {
        $view = 'RegardProductsBundle:Products:addEditProducts.html.twig';
		
		$request = $this->get('request');
		$product = new Product();
		
		$form = $this->createForm(new ProductType, $product);
		
		if ('POST' == $request->getMethod()) {
			$form->bind($request);
			
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$em->persist($product);
                $em->flush();
				
				$this->get('session')->getFlashBag()->add('notice', 'Produit ajouté');
				
                // redirect to avoid resubmission
                return new RedirectResponse($this->generateUrl('regard_list_products', array('brandId' => $brandId)));
			} else {
				$this->get('session')->getFlashBag()->add('notice', 'Erreur : Formulaire invalide');
			}
		}
        
        return $this->render($view, array('form' => $form->createView(),
                                        'product' => $product,
										'brandId' => $brandId));
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
	 * @param String $productId
     * @return render view
     */
    public function editProductsAction($productId) 
    {
        $view = 'RegardProductsBundle:Products:addEditProducts.html.twig';
		
		$request = $this->get('request');
		
		if (!$product = $this->getDoctrine()->getManager()->getRepository('RegardProductsBundle:Product')->find($productId)) {
			throw new NotFoundHttpException('Ce produit n\'existe pas');
		}
		
		$form = $this->createForm(new ProductType, $product);
		
		if ('POST' == $request->getMethod()) {
			$form->bind($request);
			
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$em->persist($product);
                $em->flush();
				
				$this->get('session')->getFlashBag()->add('notice', 'Produit modifié');
				
                // redirect to avoid resubmission
                return new RedirectResponse($this->generateUrl('regard_list_products', array('brandId' => $product->getBrandId())));
			}
		}
        
        return $this->render($view, array('form' => $form->createView(),
                                        'product' => $product,
										'brandId' => $product->getBrandId()));
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
	 * @param String $productId
     * @return render view
     */
    public function removeProductsAction($productId) 
    {
		if (!$product = $this->getDoctrine()->getManager()->getRepository('RegardProductsBundle:Product')->find($productId)) {
			throw new NotFoundHttpException('Ce produit n\'existe pas');
		}
		
		$em = $this->getDoctrine()->getManager();
		$em->remove($product);
		$em->flush();
		
		$this->get('session')->getFlashBag()->add('notice', 'Produit supprimé');
				
		// redirect to avoid resubmission
		return new RedirectResponse($this->generateUrl('regard_list_products', array('brandId' => $product->getBrandId())));
    }
	
	/**
     * @Secure(roles="ROLE_ADMIN")
     * @return render view
     */
    public function addBrandAction() 
    {
        $view = 'RegardProductsBundle:Products:addEditBrand.html.twig';
		
		$request = $this->get('request');
		$brand = new Brand();
		
		$form = $this->createForm(new BrandType, $brand);
		
		if ('POST' == $request->getMethod()) {
			$form->bind($request);
			
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$em->persist($brand);
                $em->flush();
				
				$this->get('session')->getFlashBag()->add('notice', 'Marque ajoutée');
				
                // redirect to avoid resubmission
                return new RedirectResponse($this->generateUrl('regard_list_brand'));
			} else {
				$this->get('session')->getFlashBag()->add('notice', 'Erreur : Formulaire invalide');
			}
		}
        
        return $this->render($view, array('form' => $form->createView(),
                                        'brand' => $brand));
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
	 * @param String $brandId
     * @return render view
     */
    public function editBrandAction($brandId) 
    {
        $view = 'RegardProductsBundle:Products:addEditBrand.html.twig';
		
		$request = $this->get('request');
		
		if (!$brand = $this->getDoctrine()->getManager()->getRepository('RegardProductsBundle:Brand')->find($brandId)) {
			throw new NotFoundHttpException('Cette marque n\'existe pas');
		}
		
		$form = $this->createForm(new BrandType, $brand);
		
		if ('POST' == $request->getMethod()) {
			$form->bind($request);
			
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$em->persist($brand);
                $em->flush();
				
				$this->get('session')->getFlashBag()->add('notice', 'Marque modifiée');
				
                // redirect to avoid resubmission
                return new RedirectResponse($this->generateUrl('regard_list_brand'));
			}
		}
        
        return $this->render($view, array('form' => $form->createView(),
                                        'brand' => $brand));
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
	 * @param String $brandId
     * @return render view
     */
    public function removeBrandAction($brandId) 
    {
		if (!$brand = $this->getDoctrine()->getManager()->getRepository('RegardProductsBundle:Brand')->find($brandId)) {
			throw new NotFoundHttpException('Cette marque n\'existe pas');
		}
		
		$em = $this->getDoctrine()->getManager();
		$em->remove($brand);
		$em->flush();
		
		$repoProducts = $this->getDoctrine()->getManager()->getRepository('RegardProductsBundle:Product');
		
		$products = $repoProducts->findBy(array('brandId' => $brandId));
		
		foreach ($products as $product) {
			$em->remove($product);
		}
		
		$em->flush();
		
		$this->get('session')->getFlashBag()->add('notice', 'Marque et produits associés supprimés');
				
		// redirect to avoid resubmission
		return new RedirectResponse($this->generateUrl('regard_list_brand'));
    }
	
	public function __toString()
	{
		return strval($this->id);
	}

}
